import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Date;

public class NTPTime {
	double localClockOffset;

	NTPTime(String serverName) {
		try {
			DatagramSocket socket = new DatagramSocket();
			InetAddress address = InetAddress.getByName(serverName);
			byte[] buf = new NtpMessage().toByteArray();
			DatagramPacket packet = new DatagramPacket(buf, buf.length,
					address, 123);

			NtpMessage.encodeTimestamp(packet.getData(), 40,
					System.currentTimeMillis() / 1000.0D + 2208988800.0D);

			socket.send(packet);

			packet = new DatagramPacket(buf, buf.length);
			socket.receive(packet);

			double destinationTimestamp = System.currentTimeMillis() / 1000.0D + 2208988800.0D;

			NtpMessage msg = new NtpMessage(packet.getData());

			this.localClockOffset = ((msg.receiveTimestamp
					- msg.originateTimestamp + (msg.transmitTimestamp - destinationTimestamp)) / 2.0D);

			socket.close();
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public Long getTime() {
		return Long
				.valueOf((long) (new Date().getTime() - this.localClockOffset));
	}
}